package com.kevin.enterprise.controller;

import com.kevin.enterprise.service.LoginService;
import com.kevin.enterprise.service.impl.LoginServiceImpl;

import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "LoginServlet")
public class LoginServlet extends HttpServlet {

    private LoginService loginService = new LoginServiceImpl();


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri=request.getRequestURI();
        uri=uri.substring(31);

        if("login".equals(uri)){
            dologin(request,response);
        }else  if("exit".equals(uri)){
            HttpSession session=request.getSession();
            session.invalidate();//将session设置为失效，一般在退出时使用
            response.sendRedirect("login.jsp");
        }
    }

    /**
     * 转发的功能是将用户对当前JSP页面或servlet的请求转发给另一个JSP页面或servlet。
     * request.getRequestDispatcher("login.jsp");
     */
    private void dologin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String userName = request.getParameter("name");
        String password =request.getParameter("password");

        if(userName.isEmpty() || "123".equals(userName)){//使用==判断不成功
            //重定向方法void sendRedirect(String location)
            //将用户重新定向到另一个JSP页面或servlet。
            System.out.println("name1:"+userName+",password:"+password);
            response.sendRedirect("login.jsp");
            return;
        }

        if (loginService.loginCheck(userName,password)) {

            HttpSession session=request.getSession();
            session.setAttribute("username",userName);
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
            requestDispatcher.forward(request, response);
        }else{
            response.sendRedirect("login.jsp");
            return;
        }
    }
}
